package com.hmy.uaa.common.security;


import com.hmy.uaa.bo.response.RoleResponse;
import com.hmy.uaa.dto.UserDTO;
import com.hmy.uaa.mapper.RoleMapper;
import com.hmy.uaa.mapper.UserMapper;
import com.hmy.uaa.service.DepartmentService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import com.hmy.uaa.po.User;

import javax.annotation.Resource;


/**
 * @author xiongwei
 * @ClassName JwtTokenEnhancer
 * @Description Jwt token 扩展
 * @date 2019-07-05
 **/
@Component
@Slf4j
@RequiredArgsConstructor
public class JwtTokenEnhancer implements TokenEnhancer {

    /**
     * 客户端模式
     */
    String GRANT_TYPE_CLIENT = "client_credentials";


    @Resource
    private  UserMapper userMapper;

    @Resource
    private  RoleMapper roleMapper;

    @Resource
    private  DepartmentService departmentService;

    @Override
    public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
        if (GRANT_TYPE_CLIENT.equals(authentication.getOAuth2Request().getGrantType())) {
            return accessToken;
        }

        String phone = authentication.getName();

        User user = userMapper.getUserInfo(phone);
        Map<String, Object> info = new HashMap<>();
        info.put(UserDTO.PHONE, phone);
        info.put(UserDTO.ID, user.getId());
        info.put(UserDTO.NAME, user.getName());
        info.put(UserDTO.DEPARTMENT_ID, user.getDepartmentId());

        //该用户所属企业
        Long companyId = departmentService.get(user.getDepartmentId()).getCompanyId();
        info.put(UserDTO.COMPANY_ID, companyId);
        log.info(info.toString());

        List<String> userRoleList = roleMapper.getRoleList(user.getId()).stream().map(RoleResponse::getRoleKey).collect(Collectors.toList());
        info.put(UserDTO.ROLES, userRoleList);

        ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(info);
        return accessToken;
    }
}
